package model

import (
	"database/sql"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
)

type TblFlowConfig struct {
	Id           string  `json:"id"  cbor:"id" db:"id"`
	Name         string  `json:"name" cbor:"name" db:"name"`
	Ty           int     `json:"ty" cbor:"ty" db:"ty"`
	FlowMultiple float64 `json:"flow_multiple" cbor:"flow_multiple" db:"flow_multiple"`
}

type flowConfigData struct {
	D []TblFlowConfig `json:"d"`
	T int             `json:"total"`
	S uint            `json:"s"`
}

func FlowConfigUpdate(id string, data TblFlowConfig) error {

	record := g.Record{
		"flow_multiple": data.FlowMultiple,
	}
	query, _, _ := dialect.Update("tbl_flow_config").Set(&record).Where(g.Ex{"id": id}).ToSQL()

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return nil
}

func FlowConfigList(page, pageSize uint, ex g.Ex) (flowConfigData, error) {

	data := flowConfigData{}
	t := dialect.From("tbl_flow_config")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT(1)).Where(ex).ToSQL()

		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	offset := (page - 1) * pageSize
	query, _, _ := t.Select(colsFlowConfig...).Where(ex).Offset(offset).Limit(pageSize).Order(g.C("id").Asc()).ToSQL()

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	data.S = pageSize
	return data, nil
}
